<?php
/**
 * @name        Simple Photo Gallery
 * @version	1.0: images.php
 * @since       Joomla 1.5
 * @subpackage	com_simplephotogallery
 * @author      Apptha
 * @copyright   Copyright (C) 2011 Powered by Apptha
 * @license     GNU/GPL http://www.gnu.org/copyleft/gpl.html
 * @abstract    Images model for listing and create new images.
 */
/* no direct access*/
defined('_JEXEC') or die('Restricted access');
jimport( 'joomla.application.component.model' );

global $mainframe;

$mainframe = JFactory::getApplication();

class SimplephotogalleryModelimages extends JModel
{
	/* default display of images */
    function getimage() {

        global $option, $mainframe, $albumtot, $albumval;

        /* table ordering */
        $mainframe = JFactory::getApplication();
        $filter_order = $mainframe->getUserStateFromRequest($option . 'filter_order', 'filter_order', 'title', 'cmd');
        $filter_order_Dir = $mainframe->getUserStateFromRequest($option . 'filter_order_Dir', 'filter_order_Dir', 'asc', 'word');
        $filter_id = $mainframe->getUserStateFromRequest($option . 'filter_id', 'filter_id', '', 'int');

        // search filter
        $search = $mainframe->getUserStateFromRequest($option . 'search', 'search', '', 'string');

        // page navigation
        $limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
        $limitstart = $mainframe->getUserStateFromRequest('global.list.limitstart', 'limitstart', 0, 'int');
        $lists['order_Dir'] = $filter_order_Dir;
        $lists['order'] = $filter_order;

        $db = & JFactory::getDBO();
        $albumid = "";
        $albumquery = "SELECT * FROM #__simplephotogallery_album order by id asc";
        $db->setQuery($albumquery);
        $albumval = $db->loadObjectList();

        $albumid = JRequest::getVar('albumid');
        if ($albumid)
        {
            $albumid = $albumid;
        }
        else
        {
        	$albumval[0]->id = isset($albumval[0]->id)?$albumval[0]->id:'';
            $albumid = $albumval[0]->id;
        }
        $query = "SELECT count(*) FROM #__simplephotogallery_images where album_id='" . $albumid . "'";
        $db->setQuery($query);
        $total = $db->loadResult();

        jimport( 'joomla.html.pagination' );
        $pageNav = new JPagination($total, $limitstart, $limit);

        if ((JRequest::getVar('album_id', '', 'get', 'int')) != "") 
        {
            $albumid = JRequest::getVar('albumid', '', 'get', 'int');
            $where = " where album_id='" . $albumid . "'";
            JRequest::setVar('hid_albumid',$albumid);
        }
        else if ($albumid != "") 
        {
            $where = " where album_id='" . $albumid . "'";
        } else {
            $where = "";
        }
        if ($filter_order) 
        {
            //sorting order
            $query = "SELECT a.*,b.album_name FROM #__simplephotogallery_images a inner join #__simplephotogallery_album 
            b on b.id = a.album_id   " . $where . "  order by $filter_order $filter_order_Dir LIMIT $pageNav->limitstart,$pageNav->limit";
            $db->setQuery($query);
            $rows = $db->loadObjectList();
        }
        if ($search) 
        {
            //sorting order
            $query ="SELECT a.*,b.album_name FROM #__simplephotogallery_images a inner join #__simplephotogallery_album b on b.id = a.album_id  where title LIKE '%$search%'";
            $db->setQuery($query);
            $rows = $db->loadObjectList();
        }
        if ($db->getErrorNum()) 
        {
            echo $db->stderr();
            return false;
        }
        $images = array('pageNav' => $pageNav, 'limitstart' => $limitstart, 'lists' => $lists, 'option' => $option, 'row' => $rows, 'albumval' => $albumval, 'album' => $albumid);

        return $images;
    }
    
    //Function to get setting details from the database.
	function settings()
    {
        global $option, $mainframe;
        $db =& JFactory::getDBO();

        $query = "SELECT count(*) FROM #__simplephotogallery_settings";
        $db->setQuery( $query);
        $total = $db->loadResult();

        $query = "SELECT * FROM #__simplephotogallery_settings  ";
        $db->setQuery( $query );
        $rows = $db->loadObjectList();

        if ($db->getErrorNum()) {
            echo $db->stderr();
            return false;
        }
        $settings = array('option'=>$option,'row'=>$rows);
        return $settings;
    }
    
    //Function to get album list to add new images.
	function getNewimages() 
	{
        $imagesTableRow = & JTable::getInstance('images', 'Table');
        $imagesTableRow->id = 0;
        $imagesTableRow->image = '';
        $imagesTableRow->image = '';
        $imagesTableRow->title = '';
        $imagesTableRow->description = '';
        $imagesTableRow->ordering = '';
        $imagesTableRow->singleimg = '';
        $imagesTableRow->published = '';
        $imagesTableRow->albumid = '';
        $imagesTableRow->albcover = '';

        $db = & JFactory::getDBO();
        $albumquery = "SELECT * FROM #__simplephotogallery_album";
        $db->setQuery($albumquery);
        $albumval = $db->loadObjectList();
        $images = array('imagesTableRow' => $imagesTableRow, 'albumval' => $albumval);
        return $images;
    }
    
    //Function to save new image to database.
	function saveImagesNew($images)
	{
		
		$validAliasName = '';
		//$validAliasName = array();
		$text = $images['alias_name'];
		$textSplit = str_split($text);
		foreach($textSplit as $key=>$val)
		{
			if (preg_match('/^([a-zA-Z0-9\-\_\ ]+)$/', $val))
			 {  
				 $validAliasName .= $val;
		}    
		}
		//print_r($images);
		$albumId = $images['album_id'];
		$aliasName = $validAliasName;
		$db = & JFactory::getDBO();
		$query = "SELECT sortorder FROM #__simplephotogallery_images where album_id = ". $albumId." order by id desc limit 1";
    	$db->setQuery( $query );
       	$rows = $db->loadRow();
		if(!empty($images['id']))
		{
       		$query = "SELECT id FROM #__simplephotogallery_images where id != ".$images['id']." AND album_id = ".$albumId." AND alias_name = '".$aliasName."'";
		}
		else 
		{
			$query = "SELECT id FROM #__simplephotogallery_images where album_id = ".$albumId." AND alias_name = '".$aliasName."'";
		}
		$db->setQuery( $query);
        $total = $db->loadResult();
        //print_r($total);die;
       
		
	    $imagesTableRow = & $this->getTable('images');
			
	    if (!$imagesTableRow->bind($images)) 
	    {
	    	JError::raiseError(500, 'Error binding data');
	    }
	 	if(!empty($total))
        {
        	$aliasName = $aliasName.'-'.time();
        	$imagesTableRow->alias_name = $aliasName;
        }
        else 
        {
        	$imagesTableRow->alias_name = $aliasName;
        }
        
		if(!isset($rows[0]))
		{
			$imagesTableRow->sortorder = 1;
		}
		else 
		{
	    	$imagesTableRow->sortorder = $rows[0] + 1;
		}
	    if (!$imagesTableRow->check()) 
	    {
	    	JError::raiseError(500, 'Invalid data');
	    }
		if (!$imagesTableRow->store()) 
		{
	    	$this->setError($this->_db->getErrorMsg());
	        return false;
	    }
	}
	
	//Function to set image cover to album.
	function setImage() 
	{
        $row = & JTable::getInstance('images', 'Table');
        $cid = JRequest::getVar('cid', array(0), 'get', 'array');
        $aid = JRequest::getVar('albumid', array(0), 'get', 'int');
        $set = JRequest::getVar('set', array(0), 'get', 'int');
        $db = & JFactory::getDBO();
        if ($set == 1) 
        {
            $query1 = "update #__simplephotogallery_images set album_cover=0 WHERE album_id='$aid'";
            $query = "update #__simplephotogallery_images set album_cover=1 WHERE id = '$cid[0]' and album_id='$aid'";

            $db->setQuery($query1);
            $db->query();

            $db->setQuery($query);
            $db->query();
        } else if ($set == 0) 
        {
            $query = "update #__simplephotogallery_images set album_cover=0 WHERE id = '$cid[0]' and album_id='$aid'";

            $db->setQuery($query);
            $db->query();
        }
    }
    
	/* triggered during editing of an image */
    function getimages($id) {
        global $option, $albumval, $albumtot;

        $row = & JTable::getInstance('images', 'Table');
        $cid = JRequest::getVar('cid', array(0), '', 'array');
        $id = $cid[0];
        $row->load($id);

        $db = & JFactory::getDBO();
        $albumquery = "SELECT * FROM #__simplephotogallery_album";
        $db->setQuery($albumquery);
        $albumval = $db->loadObjectList();

        $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $row->published);
        $images = array('option' => $option, 'row' => $row, 'lists' => $lists, 'albumval' => $albumval);
        return $images;
    }
    
    //Function to update the existing image.
	function saveimages($images) 
	{
        $db = & JFactory::getDBO();
        $title = $images['title'];
        $albumid = $images['album_id'];
        $description = $images['description'];
        $published = $images['published'];
        $alias_name = $images['alias_name'];
		if(empty($alias_name))
		{
			$aliasName = $title;
			//$al = $_REQUEST['alias_name'];
			$aliasName = strtolower(trim($aliasName));
			$aliasName = str_replace(' ','-',$aliasName);
		}
		else 
		{
			//$aliasName = JRequest::getVar('alias_name');
			//$al = $_REQUEST['alias_name'];
			$aliasName = strtolower(trim($alias_name));
			$aliasName = str_replace(' ','',$aliasName);
		}
        
        
        
		$albumId = JRequest::getVar('album_id');
		//$query = "SELECT id FROM #__simplephotogallery_images where album_id = ".$albumId." AND alias_name = '".$aliasName."'";
		echo $query = "SELECT id FROM #__simplephotogallery_images where id != ".$images['id']." AND album_id = ".$albumId." AND alias_name = '".$aliasName."'";
		$db->setQuery( $query);
        $total = $db->loadResult();
        if(!empty($total))
        {
        	$aliasName = $aliasName.'-'.time();
        }
        $imgfilename = explode("/",JRequest::getVar("image"));
        if(!isset($imgfilename[2]))
        $imgfilename[2] = "";
        
        $query = "update #__simplephotogallery_images set image = '$imgfilename[2]', title ='$title',description='$description',album_id='$albumid',alias_name='$aliasName',published='$published' WHERE id = '$images[id]'";
		
            
        $db->setQuery($query);
        $db->query();
        
    }
    
    //Function to publish or unpublish the images from the list.
	function pubimages($arrayIDs) 
	{
		//print_r($_REQUEST);
		$albumid = JRequest::getVar('albumid');
		
        if ($arrayIDs['task'] == "publish") 
        {
            $publish = 1;
        } 
        else 
        {
            $publish = 0;
        }
        $n = count($arrayIDs['cid']);
        //$albumid = $images['albumid'][$i];
        for ($i = 0; $i < $n; $i++) 
        {
            $query = "UPDATE #__simplephotogallery_images set published=" . $publish . " WHERE id=" . $arrayIDs['cid'][$i];
            $db = $this->getDBO();
            $db->setQuery($query);
            $db->query();    
        }
        
        if($arrayIDs['task'] == "unpublish")
        {
	        for ($i = 0; $i < $n; $i++) 
	        {
	        	
	            $query = "UPDATE #__simplephotogallery_images set sortorder= sortorder - 1 WHERE album_id = ".$albumid." AND id >=" . $arrayIDs['cid'][$i];
	            
	            $db = $this->getDBO();
	            $db->setQuery($query);
	            $db->query();    
	        }
        }
        else
        {
        for ($i = 0; $i < $n; $i++) 
        {
            $query = "UPDATE #__simplephotogallery_images set sortorder= sortorder + 1 WHERE album_id = ".$albumid." AND id >=" . $arrayIDs['cid'][$i];
            $db = $this->getDBO();
            $db->setQuery($query);
            $db->query();    
        }
        }

	}
	
	//Function to set images as featured or unfeatured image.
	function featuredpublish($arrayIDs)
	{
	if ($arrayIDs['task'] == "featuredpublish") {
            $publish = 1;
        } else {
            $publish = 0;
        }
        $n = count($arrayIDs['cid']);
        //$albumid = $images['albumid'][$i];
        for ($i = 0; $i < $n; $i++) 
        {
            $query = "UPDATE #__simplephotogallery_images set is_featured=" . $publish . " WHERE id=" . $arrayIDs['cid'][$i];
            $db = $this->getDBO();
            $db->setQuery($query);
            $db->query();     
        }
	}
	
	//Function to get settings details.
	function getsettings()
    {
        global $option, $mainframe;
        $db =& JFactory::getDBO();

        $query = "SELECT count(*) FROM #__simplephotogallery_settings";
        $db->setQuery( $query);
        $total = $db->loadResult();

        $query = "SELECT * FROM #__simplephotogallery_settings  ";
        $db->setQuery( $query );
        $rows = $db->loadObjectList();

        if ($db->getErrorNum()) 
        {
            echo $db->stderr();
            return false;
        }
        $settings = array('option'=>$option,'row'=>$rows);
        return $settings;
    }
    
    //Function to delete the images from the list.
 	function deleteimages($arrayIDs) 
 	{
 		$albumid = JRequest::getVar('albumid');
 		//print_r($arrayIDs);
 		$n = count($arrayIDs);
 		//print_r($_REQUEST);
 		for ($i = 0; $i < $n; $i++) 
        {
            $query = "UPDATE #__simplephotogallery_images set sortorder= sortorder - 1 WHERE album_id = ".$albumid." AND id >=" . $arrayIDs[$i];
            $db = $this->getDBO();
            $db->setQuery($query);
            $db->query();     
        }
        $query = "DELETE FROM #__simplephotogallery_images WHERE id IN (" . implode(',', $arrayIDs) . ")";
        $db = $this->getDBO();
        $db->setQuery($query);
        $db->query();
    }
    
}